#include <func.h>

typedef struct
{
    int id;
    int money;
    pthread_mutex_t mutex;
} Account;

Account acct1 = {1, 100, PTHREAD_MUTEX_INITIALIZER};
Account acct2 = {2, 900, PTHREAD_MUTEX_INITIALIZER};

void* start_routine1(void* arg)
{
    int num = (int)arg;

    if(acct1.id > acct2.id)
    {
        pthread_mutex_lock(&acct1.mutex);
        pthread_mutex_lock(&acct2.mutex);
    }
    else
    {
        pthread_mutex_lock(&acct2.mutex);
        pthread_mutex_lock(&acct1.mutex);
    }

    acct1.money -= 100;
    acct2.money += 100;
    fprintf(stderr, "0x%lu acct1 --> acct2 100$\n", pthread_self());

    pthread_mutex_unlock(&acct1.mutex);
    pthread_mutex_unlock(&acct2.mutex);
    return NULL;
}
void* start_routine2(void* arg)
{
    int num = (int)arg;

    if(acct1.id > acct2.id)
    {
        pthread_mutex_lock(&acct1.mutex);
        pthread_mutex_lock(&acct2.mutex);
    }
    else
    {
        pthread_mutex_lock(&acct2.mutex);
        pthread_mutex_lock(&acct1.mutex);
    }

    acct2.money -= 900;
    acct1.money += 900;
    fprintf(stderr, "0x%lu acct2 --> acct1 900$\n", pthread_self());

    pthread_mutex_unlock(&acct1.mutex);
    pthread_mutex_unlock(&acct2.mutex);

    return NULL;
}

int main(void)
{
    int err;
    pthread_t thread1, thread2;

    //1给2转100
    err = pthread_create(&thread1, NULL, start_routine1, (void*)100);
    if(err)
        error(1, err, "pthread_create");
    //2给1转900
    err = pthread_create(&thread2, NULL, start_routine2, (void*)900);
    if(err)
        error(1, err, "pthread_create");

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);

    return 0;
}
